#!/bin/bash

# 检查 landscape2 是否已安装
if ! command -v landscape2 &> /dev/null; then
    echo "landscape2 未安装，正在安装..."
    curl --proto '=https' --tlsv1.2 -LsSf https://github.com/cncf/landscape2/releases/download/v0.13.0/landscape2-installer.sh | sh

    # 更新环境变量
    source $HOME/.cargo/env

    # 再次检查是否安装成功
    if ! command -v landscape2 &> /dev/null; then
        echo "错误: landscape2 安装失败"
        exit 1
    else
        echo "landscape2 安装成功"
    fi
fi

# 检查必要的文件是否存在
required_files=(
    "./demo/landscape.yml"
    "./demo/settings.yml"
    "./demo/guide.yml"
)

for file in "${required_files[@]}"; do
    if [ ! -f "$file" ]; then
        echo "错误: 文件 $file 不存在"
        exit 1
    fi
done

# 检查 logos 目录是否存在
if [ ! -d "./demo/hosted_logos" ]; then
    echo "错误: logos 目录不存在"
    exit 1
fi

# 创建输出目录（如果不存在）
mkdir -p build

echo "开始构建 landscape..."
landscape2 build \
    --data-file ./demo/landscape.yml \
    --settings-file ./demo/settings.yml \
    --guide-file ./demo/guide.yml \
    --logos-path ./demo/hosted_logos \
    --output-dir build

if [ $? -eq 0 ]; then
    echo "构建成功完成！"
else
    echo "构建失败！"
    exit 1
fi

echo "正在启动 landscape 服务器..."
landscape2 serve --landscape-dir build

if [ $? -eq 0 ]; then
    echo "服务器已成功启动！"
else
    echo "服务器启动失败！"
    exit 1
fi